<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">编辑个人奖项</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请修改个人奖项信息。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          :pdf-url="form.pdfPath"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh;margin-bottom: 3vh ">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">修改信息</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="奖项名称" prop="title" required>
              <el-input v-model="form.title" placeholder="请填写奖项名称" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="form.authorRank" style="width: 34vw;">
                <el-option v-for="i in 13" :key="i" :label="i.toString()" :value="i"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="获奖名次" prop="awardLevel">
              <el-select v-model="form.awardLevel" placeholder="请选择获奖名次" style="width: 34vw;">
                <el-option label="一等奖" value="一等奖"></el-option>
                <el-option label="二等奖" value="二等奖"></el-option>
                <el-option label="三等奖" value="三等奖"></el-option>
                <el-option label="金" value="金"></el-option>
                <el-option label="银" value="银"></el-option>
                <el-option label="铜" value="铜"></el-option>
                <el-option label="冠" value="冠"></el-option>
                <el-option label="亚" value="亚"></el-option>
                <el-option label="季" value="季"></el-option>
                <el-option label="特等奖" value="特等奖"></el-option>
                <el-option label="优秀奖" value="优秀奖"></el-option>
                <el-option label="入围奖" value="入围奖"></el-option>
                <el-option label="优秀指导教师奖" value="优秀指导教师奖"></el-option>
                <el-option label="优秀组织奖" value="优秀组织奖"></el-option>
                <el-option label="不计等次" value="不计等次"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="奖项级别" prop="level" required>
              <el-select v-model="form.level" placeholder="请选择奖项级别" style="width: 34vw;">
                <el-option label="国际级" value="国际级"></el-option>
                <el-option label="国家级" value="国家级"></el-option>
                <el-option label="省级" value="省级"></el-option>
                <el-option label="市厅级" value="市厅级"></el-option>
                <el-option label="校级" value="校级"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="授予单位" prop="grantingUnit" required>
              <el-input v-model="form.grantingUnit" placeholder="请填写授予单位" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="获奖时间" prop="awardTime" required>
              <el-date-picker
                  v-model="form.awardTime"
                  type="date"
                  placeholder="选择日期"
                  style="width: 34vw;"
                  value-format="x">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否同步" prop="syncStatus">
              <el-select v-model="form.syncStatus" style="width: 34vw;" placeholder="请选择是否同步">
                <el-option label="是" :value="'是'"></el-option>
                <el-option label="否" :value="'否'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联课题" prop="projectId">
              <el-select
                  v-model="form.projectId"
                  placeholder="请选择本成果所属课题,以便使用结题助手功能"
                  style="width: 34vw;"
              >
                <el-option
                    v-for="project in longitudinalProjects"
                    :key="project.id"
                    :label="project.projectName"
                    :value="project.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto; padding: 10px; border-radius: 4px;">
                <!-- 表头 -->
                <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #e8e8e8;">
                  <div style="width: 60px; text-align: center;">排序</div>
                  <div style="width: 120px; margin-left: 15px;">姓名</div>
                  <div style="width: 120px; margin-left: 15px;">作者身份</div>
                  <div style="flex: 1; margin-left: 15px;">单位名称</div>
                  <div style="width: 80px; margin-left: 15px;">操作</div>
                </div>

                <!-- 作者列表 -->
                <div v-for="(author, index) in form.authorInfo" :key="index"
                     style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                  <el-select v-model="author.rank" style="width: 60px;">
                    <el-option
                        v-for="i in 13"
                        :key="i"
                        :label="i"
                        :value="i">
                    </el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 120px; margin-left: 15px;" placeholder="姓名"></el-input>

                  <el-select v-model="author.identity" style="width: 120px; margin-left: 15px;" placeholder="身份">
                    <el-option
                        v-for="item in shipOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-select v-model="author.institution" placeholder="请选择单位名称" style="flex: 1; margin-left: 15px;">
                    <el-option label="信息工程学院" value="信息工程学院"></el-option>
                  </el-select>

                  <el-button
                      type="danger"
                      size="small"
                      @click="removeAuthor(index)"
                      style="width: 80px; margin-left: 15px;">
                    删除
                  </el-button>
                </div>

                <el-button @click="addAuthor" style="margin-top: 10px;">添加作者</el-button>
              </div>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks">
              <el-input type="textarea" :rows="4" v-model="form.remarks" placeholder="请输入备注信息" style="width: 34vw;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="upload-button" style="width: 10vw;" :disabled="isSubmitting">
              {{ isSubmitting ? '保存中...' : '保 存' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import PdfPreview from "@/components/PdfPreview.vue"
import { getPersonalAwardById, updatePersonalAward } from "@/api/Manage/personalAward.js"
import {getCompletedLongitudinal, getProjectNameById} from "@/api/Research/Longitudinal.js"
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const pdfPreviewRef = ref(null)
const longitudinalProjects = ref([]) // 存储已结题的纵向课题
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const form = reactive({
  id: '',
  title: '',
  authorRank: null,
  awardLevel: '',
  level: '',
  grantingUnit: '',
  awardTime: '',
  remarks: '',
  projectId: '',
  authorInfo: [{
    rank: 1,
    name: '',
    identity: '',
    institution: '',
    corresponding: false,
    coFirstAuthor: false
  }],
  syncStatus: '',
  pdfPath: ''
})
const shipOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]
const rules = {
  title: [{ required: true, message: '请输入奖项名称', trigger: 'blur' }],
  authorRank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  level: [{ required: true, message: '请输入奖项级别', trigger: 'blur' }],
  grantingUnit: [{ required: true, message: '请输入授予单位', trigger: 'blur' }],
  awardTime: [{ required: true, message: '请选择获奖时间', trigger: 'change' }]
}

const addAuthor = () => {
  form.authorInfo.push({
    rank: form.authorInfo.length + 1,
    name: '',
    identity: '',
    institution: '',
    corresponding: false,
    coFirstAuthor: false
  })
}

const removeAuthor = (index) => {
  form.authorInfo.splice(index, 1)
}

const updatePdfPath = (newPath) => {
  form.pdfPath = newPath.firstImageUrl
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const submit = async () => {
  if (!formRef.value) return

  try {
    isSubmitting.value = true

    // 验证表单
    const valid = await new Promise((resolve) => {
      formRef.value.validate((valid) => resolve(valid))
    })
    if (!valid) {
      ElMessage.error('请填写必填项')
      return
    }

    // 如果有旋转，先保存旋转
    if (hasRotations.value && currentRotations.value.length > 0) {
      try {
        // 组装批量更新请求数据
        const batchData = {
          filePath: form.pdfPath, // PDF文件路径
          pages: currentRotations.value.map(rotation => ({
            pageNumber: rotation.pageIndex + 1, // 页码从1开始
            rotation: rotation.rotation // 旋转角度
          }))
        }

        console.log('批量更新旋转请求数据:', batchData)

        const rotationResult = await batchUpdatePdfPages(batchData)
        console.log('批量更新旋转结果:', rotationResult)

        if (rotationResult.code !== "0") {
          ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
          return
        }

        ElMessage.success('旋转保存成功')

        // 重置旋转状态
        hasRotations.value = false
        currentRotations.value = []

        // 通知PDF预览组件重新加载
        if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
          await pdfPreviewRef.value.reloadPDF(form.pdfPath)
        }

      } catch (rotationError) {
        console.error('保存旋转失败:', rotationError)
        ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
        return
      }
    }

    // 提交个人奖项信息
    const response = await updatePersonalAward(form)
    if (response.code === 1) {
      ElMessage.success('保存成功')
      router.push('/main/result/PersonalAward')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

watch(() => form.projectId, async (newProjectId) => {
  if (newProjectId) {
    const projectRes = await getProjectNameById(newProjectId);
    console.log("projectRes", projectRes)
    if (projectRes.data) {
      form.projectId = projectRes.data;
    }
  }
});

onMounted(async () => {
  const id = route.query.id
  if (id) {
    try {
      const res = await getPersonalAwardById(id)
      if (res.code === 1 && res.data) {
        const data = res.data
        if (data.awardTime) {
          data.awardTime = Number(data.awardTime)
        }
        Object.assign(form, data)
      } else {
        ElMessage.error('获取个人奖项信息失败')
      }
    } catch (error) {
      console.error('获取个人奖项信息失败:', error)
      ElMessage.error('获取个人奖项信息失败，请重试')
    }
  }

  // 获取已结题的纵向课题
  try {
    const response = await getCompletedLongitudinal();
    if (response.code === 1 && Array.isArray(response.data)) {
      longitudinalProjects.value = response.data;
    } else {
      ElMessage.error('获取结题的纵向课题失败');
    }
  } catch (error) {
    console.error('获取结题的纵向课题出错:', error);
    ElMessage.error('获取结题的纵向课题失败，请刷新页面重试');
  }
})
</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover:not(:disabled) {
  background-color: #009b77;
}

.upload-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
